package wyn.spec.edu;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ListView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import okhttp3.Request;
import okhttp3.Response;
import okhttp3.OkHttpClient;

public class ActivitySecond extends AppCompatActivity {
    private static final String TAG="ActivitySecond";
    List<Message> messagelist=null;

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        sendRequestWihtOkhttp();
    }

    private void sendRequestWihtOkhttp() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try{

                    OkHttpClient client = new OkHttpClient();

                    Request request = new Request
                            .Builder()
                            .url("http://www.yyjsx.xyz/api/message/listByCategory?messageCategory=WECHAT")
                            .build();
                    Response response = client.newCall(request).execute();
                    String body = response.body().string();
                    Log.d(TAG, body);
                    parseJson(body);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private void parseJson(String jsonStr) {
        try {
            JSONObject jobj = new JSONObject(jsonStr);
            String dataStr = jobj.getString("data");

            Gson gson = new Gson();
            messagelist = gson.fromJson(dataStr, new TypeToken<List<Message>>(){}.getType());
            // 更新UI
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    MessageAdapter fa = new MessageAdapter(ActivitySecond.this, R.layout.activity_second, messagelist);
                    ListView lv = (ListView)findViewById(R.id.imageLV);
                    lv.setAdapter(fa);
                }
            });

            for (Message m : messagelist){
                Log.d(TAG, m.getTitle());
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
